package com.zd.controller;


import com.zd.entity.Topic;
import com.zd.service.NewsService;
import com.zd.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/topic/")
public class TopicController {
    @Autowired
    private TopicService topicService;
    @Autowired
    private NewsService newsService;
    @GetMapping("list")
    public String list(Model model){
        List<Topic> topics = topicService.queryAllTopics();
        model.addAttribute("topics",topics);
        return "admin/topic_list";
    }

    @GetMapping("toadd")
    public String toAdd(){
        return "admin/topic_add";
    }

    @PostMapping("doadd")
    public String doAdd(String tname,Model model){
        if(topicService.queryTopicByTname(tname) == null){
            Topic topic = new Topic();
            topic.setTname(tname);
            Topic topic1=topicService.addTopic(topic);
            return "redirect:/topic/list";
        }else{
            model.addAttribute("error","该主题已存在！");
            model.addAttribute("tname",tname);
            return "admin/topic_add";
        }
    }

    @GetMapping("toupdate")
    public String toUpdate(Long tid,Model model){
        Topic topic=topicService.queryTopicByTid(tid);
        model.addAttribute("topic",topic);
        return "admin/topic_modify";
    }

    @PostMapping("doupdate")
    public String doUpdate(Topic topic,Model model){
        if(topicService.queryTopicByTname(topic.getTname()) == null){
            Topic topic1=topicService.updateTopic(topic);
            return "redirect:/topic/list";
        }else{
            model.addAttribute("error","该主题已存在！");
            model.addAttribute("tname",topic);
            return "admin/topic_modify";
        }
    }

    @GetMapping("/delete")
    public String delete(Long tid){
        /*if(newsService.isNewsExists(tid)){
            model.addAttribute("error","主题下存在新闻！");
        }else {

        }*/
        topicService.deleteTopic(tid);
        return "redirect:/topic/list";
    }

    @GetMapping("newsexists")
    @ResponseBody
    public Object isNewsExists(Long tid){
        boolean newsExists = newsService.isNewsExists(tid);
        return "{\"result\":\""+newsExists+"\"}";
    }
}
